//
//  ZyaJPProgressVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/3/25.
//  Copyright © 2025 aowang. All rights reserved.
//  竞拍进度

import UIKit

class ZyaJPProgressVC: TenderBaseTableController,UISearchBarDelegate {
    
    var page = 1
    
    var dataArray = [ZtbContentModel]()
    var z_zb_id = "" // 投标记录使用
     
 
    private var searchBar:UISearchBar?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "竞拍跟踪"
        self.setSearchBar()
        helper.callTableRefreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
            
        }
        
        tableView.estimatedRowHeight = 50
        tableView.rowHeight = UITableView.automaticDimension
        
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter { [unowned self] in
            self.page += 1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
        tableView.register(XSBaojiaCell.self, forCellReuseIdentifier: XSBaojiaCell.identifier)
        
        
        
        
        
        
        tableView.tableFooterView = UIView()
        
        
    }
    @objc func doneClickss() {
        self.searchBar!.resignFirstResponder()
    }
    
    func setSearchBar () {
        searchBar = TenderSearchBar(frame:CGRect(x:5,y:5,width:KSGlobal.screenW - 60,height:40))
        let toolbar = UIToolbar()
        toolbar.barStyle = UIBarStyle.default
        toolbar.sizeToFit()
        let buttonflexible = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
        let buttonDone = UIBarButtonItem(title: "完成", style: UIBarButtonItem.Style.done, target: self, action: #selector(doneClickss))
        buttonDone.tintColor = UIColor.black
        toolbar.setItems([buttonflexible, buttonDone], animated: true)
        
        searchBar!.inputAccessoryView = toolbar
        searchBar?.backgroundImage = UIImage()
       

        searchBar!.searchTextField.backgroundColor = .white
          searchBar!.searchTextField.layer.cornerRadius = 18
            searchBar!.searchTextField.layer.masksToBounds = true
        searchBar!.searchTextField.layer.borderColor = Theme.primaryColor().cgColor
       searchBar!.searchTextField.layer.borderWidth = 1
        
        
        searchBar!.text = self.helper.filterPa!.searchTitle
        searchBar!.placeholder = "搜索报价信息"
        searchBar!.delegate = self
        let searchView = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW ,height:50))
        searchView.addSubview(searchBar!)
        
 
 
        
        let moreBtn = UIButton(frame:CGRect(x:KSGlobal.screenW - 50,y:5,width:40 ,height:40))
        moreBtn.setBackgroundImage(UIImage(named: "filter_more"), for: .normal)
        moreBtn.addTouchUpInSideAction { _ in
            
            
            let window = UIApplication.shared.keyWindow!.rootViewController!.view!
           
                window.addSubview(self.slideV)
        
      
        }
        searchView.addSubview(moreBtn)
        self.tableView.tableHeaderView = searchView
    
    }
    @objc func publishAction() {
        self.helper.publishTender(controller:self)
    }
    @objc func mapAction() {
        
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        searchBar.resignFirstResponder()
        self.helper.filterPa!.searchTitle = searchBar.text.unwrap
        self.tableView.mj_header?.beginRefreshing()
    }
    
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataArray.count
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        
        
        guard let cell = tableView.dequeueReusableCell(withIdentifier: XSBaojiaCell.identifier, for: indexPath) as? XSBaojiaCell else {
            fatalError("cell error")
        }
        let one = self.dataArray[indexPath.row]
        one.innerType = .jpInfo_followTagOA
        cell.makeConstrainsts()
        cell.chujiaBtn.addTouchUpInSideAction  { [one, unowned self] btn in
            // 出价记录
            let  vc = ShowPriceRecVC( z_zb_id: one.idKey.unwrap)
            vc.billTitle = one.zTitle.unwrap
            self.navigationController?.pushViewController(vc, animated: true)
            
            
        }
        cell.one = one
        
        
        return cell
        
        
        
        
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        
        var idkey:String = ""
        // 我的招标  招投标
        idkey = self.dataArray[indexPath.row].idKey.unwrap
        
        
        go2TenderInfoController(listType: .JP, fromVC:self,idkey:idkey,voccd: "",innerType:.jpInfo_followTagOA)
        
        
        
        
    }
    func network () {
 
        
        let api = API.queryJpInfoList(z_begin_dt: self.helper.filterPa!.startDate, z_end_dt: self.helper.filterPa!.endDate,z_out_dt: self.helper.filterPa!.outDate, z_city: self.helper.filterPa!.zCity, z_price_min: self.helper.filterPa!.minMoney, z_price_max: self.helper.filterPa!.maxMoney, page: "\(page)", size: "10", z_title: self.helper.filterPa!.searchTitle, z_sort: self.helper.filterPa!.zSort, query_type: "4",z_status: self.helper.filterPa!.zStatus,followTag: "1",z_contract_state: "")
        
        
        KSNetwork.shared.doRequest(api,showHud: false) { [weak self] (data:BaseResult<ZtbContentModel>) in
            guard let `self` = self else { return }
            if data.flag == TRUE {
                if let infos = data.infoArrCombine {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    if infos.count < 10 {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    } else {
                        self.tableView.mj_footer?.endRefreshing()
                    }
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
    }
    
    
    deinit {
        print("tenderfirst 销毁")
    }
}


extension ZyaJPProgressVC:XYXFilterMenuDataSource {
    // 头部显示要改变的时候回调此方法
    func menu(_ menu: XYXFilterMenu, shouldChange title: String, for indexPath: XYXFilterIndexPath) -> String? {
        
        let titlesStr =  self.helper.titles_jp[indexPath.column!]
        var theTitle = title
        if theTitle == "全部." {
            theTitle = provinceArr[indexPath.row!]
        }
        if theTitle == "全部" {
            theTitle = titlesStr
        }
        return theTitle
    }
    // 每个列展示的数组
    func menu(_ menu: XYXFilterMenu, numberOfRowsAt indexPath: XYXFilterIndexPath) -> Int {
        guard indexPath.column != nil else {
            return 0
        }
        switch indexPath.column! {
        case 0:
            return  zhuangtaiArr_jp.count
        case 1:
            return provinceArr.count
        case 2:
            
            return self.helper.source_jp_status.count
            
            
        case 3:
            return 1
        default:
            return 0
        }
    }
    
    func menu(_ menu: XYXFilterMenu, numberOfItemsAt indexPath: XYXFilterIndexPath) -> Int {
        guard indexPath.column != nil && indexPath.row != nil else {
            return 0
        }
        switch indexPath.column! {
        case 1:
            return cityDic[provinceArr[indexPath.row!]]!.count
        case 3:
            return 1
        default:
            return 0
        }
    }
    // 各个过滤项的 标题数组
    func menu(_ menu: XYXFilterMenu, titleOfRowAt indexPath: XYXFilterIndexPath) -> String {
        let defaultString = ""
        guard indexPath.column != nil && indexPath.row != nil else {
            return defaultString
        }
        switch indexPath.column! {
        case 0: // 状态（招标的时候）
            return  zhuangtaiArr_jp[indexPath.row!]
        case 1: // 区域
            return provinceArr[indexPath.row!]
            
        case 2: // 时间
            
            return self.helper.source_jp_status[indexPath.row!]
            
            
        default:
            return defaultString
        }
    }
    
    func menu(_ menu: XYXFilterMenu, titleOfItemAt indexPath: XYXFilterIndexPath) -> String {
        let defaultString = ""
        guard indexPath.column != nil && indexPath.row != nil && indexPath.item != nil else {
            return defaultString
        }
        if indexPath.column == 1 {
            var cityArr = cityDic[provinceArr[indexPath.row!]]!
            if cityArr.count > 1 {
                cityArr.insert("全部.", at: 0)
            } else {
                
            }
            return cityArr[indexPath.item!]
        }
        return defaultString
    }
    // 大菜单数量
    func numberOfColumns(menu: XYXFilterMenu) -> Int {
        return  self.helper.titles_jp.count
    }
    // 大标题数据
    func menu(_ menu: XYXFilterMenu, titleOfColumnAt index: Int) -> String {
        return  self.helper.titles_jp[index]
    }
    // 菜单的样式，单列表 多列表   collectionview等
    func menu(_ menu: XYXFilterMenu, typeOfColumn: Int) -> XYXFilterView.ColumnType.RawValue {
        switch typeOfColumn {
        case 1:
            return XYXFilterView.ColumnType.TableViewTwo.rawValue
        case 0,2:
            return XYXFilterView.ColumnType.TableViewOne.rawValue
        default:
            return XYXFilterView.ColumnType.collectionViewType.rawValue
        }
    }
    
    func menu(_ menu: XYXFilterMenu, widthOf tableView: UITableView, at column: Int) -> CGFloat {
        if column == 1 {
            if tableView.tag == XYXFilterView.firstTabViewTag{
                return XYX_SCREEN_WIDTH * 0.35
            }else if tableView.tag == XYXFilterView.secondTabViewTag{
                return XYX_SCREEN_WIDTH * 0.65
            }
        }
        return XYX_SCREEN_WIDTH/2
    }
    
    // 菜单向下展开的高度
    func menu(_ menu: XYXFilterMenu, filterContentHeightAt column: Int) -> CGFloat {
        if column == 3 {
            return 200.0
        } else {
            return 300.0
        }
        
    }
    
}

extension ZyaJPProgressVC:XYXFilterMenuDelegate {
    func menu(_ menu:XYXFilterMenu, tapIndex: Int) {
        print(tapIndex)
    }
    func menu(_ menu: XYXFilterMenu, tapIndexShowEnable: Int) -> Bool {
        print(tapIndexShowEnable)
        if tapIndexShowEnable == 3 {
            self.helper.listFilterAction(listType: .JP)
            return false
        } else {
            return true
        }
    }
}

